package com.chushouya.manager.service.common;

import com.chushouya.common.applet.AlipayClient;
import com.chushouya.manager.dao.entity.ProgramEntity;
import com.general.framework.core.lang.Integers;
import com.general.framework.core.lang.Validate;
import com.general.framework.web.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 支付宝客户端工厂
 */
@Slf4j
public class AlipayClientFactory {

    private static final ConcurrentMap<String, AlipayClient> cache = new ConcurrentHashMap<>();

    /**
     * 获取支付宝客户端实例
     *
     * @param appid 小程序appid
     */
    public synchronized static AlipayClient getInstance(String appid) {
        Validate.isBlank(appid, "小程序appid不能为空");
        if (!cache.containsKey(appid)) {
            ProgramEntity alipay = selectAlipay(appid);
            log.debug("==========>支付宝小程序配置：{}", alipay);
            if (Integers.isNullOrZero(alipay.getSignType())) {
                //公私钥模式
                cache.put(appid, new AlipayClient(appid, alipay.getPrivateKey(), alipay.getAlipayPublicKey(), alipay.getSecret()));
            } else {
                //证书模式
                cache.put(appid, new AlipayClient(appid, alipay.getPrivateKey(),alipay.getSecret()));
            }
        }
        return cache.get(appid);
    }

    /**
     * 查询支付宝小程序
     */
    private static ProgramEntity selectAlipay(String appid) {
        ProgramEntity alipay = SpringHolder.ALIPAY_PROGRAM_SERVICE.selectByAppId(appid);
        Validate.isNull(alipay, "小程序不存在");
        return alipay;
    }

    private static class SpringHolder {
        private static final AlipayProgramService ALIPAY_PROGRAM_SERVICE = SpringUtils.getBean(AlipayProgramService.class);
    }

}
